package gu.sql2java.generator;

import static gu.sql2java.generator.GeneratorConfig.CONFIG;
import static com.google.common.base.Preconditions.checkNotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gitee.l0km.com4j.base.MiscellaneousUtils;

public class Generator {
	private static final Logger logger = LoggerFactory.getLogger(Generator.class);

	private static final Properties DEFAULT_PROP;
	static {
		DEFAULT_PROP = new Properties();
		try (InputStream stream=Generator.class.getResourceAsStream("/sql2java.properties")){
			DEFAULT_PROP.load(stream);
		} catch (IOException e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	private static Properties prop;
	public static void main(String ...argv) {
		CONFIG.parseCommandLine(argv);
		prop = new Properties(DEFAULT_PROP);
		File propFile = CONFIG.getPropFile();
		if(!propFile.isFile()){
			logger.error("NOT FOUND file {}", propFile);
			System.exit(-1);
		}
		try (InputStream is = new FileInputStream(propFile)){
			prop.load(is);
			CodeWriter cw = new CodeWriter(null, prop);
			cw.log("database properties initialization");
			Database db = new Database();
			db.setDriver(getPropertyRequired("jdbc.driver"));
			db.setUrl(getPropertyRequired("jdbc.url"));
			db.setUsername(getProperty("jdbc.username"));
			db.setPassword(getProperty("jdbc.password"));
			db.setCatalog(getProperty("jdbc.catalog"));
			db.setSchema(getProperty("jdbc.schema"));
			db.setTableNamePattern(getProperty("jdbc.tablenamepattern"));
			db.setUsingTablenamepatternAsSamePrefix(getProperty("jdbc.tablenamepattern.force"));
			CodeWriter writer = new CodeWriter(db, prop);

			List<String> tableTypes = MiscellaneousUtils.elementsOf(getProperty("jdbc.tabletypes", "TABLE"));
			db.setTableTypes(tableTypes.toArray(new String[tableTypes.size()]));
			db.load();
			writer.process();
		} catch (Exception e) {
			if(CONFIG.isTrace()){
				e.printStackTrace();
			}else{
				System.out.println(e.getMessage());
			}
			System.exit(1);
		}
	}

	public static String getProperty(String property) {
		String s = prop.getProperty(property);
		return s != null ? s.trim() : s;
	}

	public static String getProperty(String property, String defaultVal) {
		String s = prop.getProperty(property,defaultVal);
		return s != null ? s.trim() : s;
	}
	public static String getPropertyRequired(String property) {
		return checkNotNull(getProperty(property),"Missing property %s",property).trim();
	}

}